package com.task.submitter.controllers.images.transform;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.tools.cloudstorage.GcsFileOptions;
import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.appengine.tools.cloudstorage.GcsOutputChannel;
import com.google.appengine.tools.cloudstorage.GcsService;
import com.google.appengine.tools.cloudstorage.GcsServiceFactory;
import com.google.appengine.tools.cloudstorage.RetryParams;
import com.task.submitter.controllers.BaseController;
import com.task.submitter.dto.StoredImageDto;

public abstract class BaseImageTransformController extends BaseController {

	public abstract Image transform(Image oldImage);
	
	public void submit(StoredImageDto dto) throws IOException {
		
		 BlobKey blobKey = new BlobKey(dto.getBlobKey());
	     Image oldImage = ImagesServiceFactory.makeImageFromBlob(blobKey);
	     
	     Image newImage = transform(oldImage);

	     GcsService gcsService = GcsServiceFactory.createGcsService(RetryParams.getDefaultInstance());
	     GcsFilename filename = new GcsFilename("love4gridy", dto.getNameId());
	     GcsOutputChannel outputChannel =
	    		    gcsService.createOrReplace(filename, GcsFileOptions.getDefaultInstance());
	    outputChannel.write(ByteBuffer.wrap(newImage.getImageData()));
	    outputChannel.close();
	    BlobKey newBlobKey = BlobstoreServiceFactory.getBlobstoreService().createGsBlobKey("/gs/" + filename.getBucketName() +"/"+ filename.getObjectName());
	    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
	    String date = format.format(Calendar.getInstance().getTime());
	    String newName = String.format("%s-%s-%s", filename.getObjectName(), dto.getTransform(), date);
	    
	    Key userCtxKey = KeyFactory.createKey("UserContext", dto.getUserName());
		Entity imgKey = new Entity("ImgKey", userCtxKey);
		imgKey.setProperty("key", newBlobKey.getKeyString());
		imgKey.setProperty("nameId", newName);
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		datastore.put(imgKey); 
	    
   }
	
}
